﻿using System.Collections.Generic;
using System.Linq;

namespace Tuxedo
{
	internal static class CsProjReader
	{
		public static CsProjData Read(string directory, string contents)
		{
			byte[] contentsBytes = contents.ToCharArray().Select<char, byte>(c => (byte)c).ToArray();
			//System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.MemoryStream(contentsBytes));
			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.LoadXml(contents);
			//string foo = reader.ReadInnerXml();

			List<string> codeFiles = new List<string>();
			List<string> embedFiles = new List<string>();

			//System.Xml.XmlReader st = reader.ReadSubtree();
			foreach (System.Xml.XmlNode rootChild in doc.ChildNodes)
			{
				if (rootChild.Name == "xml")
				{
					// okidoke
				}
				else if (rootChild.Name == "Project")
				{
					foreach (System.Xml.XmlNode projectComponent in rootChild.ChildNodes)
					{
						string name = projectComponent.Name;
						if (name == "PropertyGroup")
						{

						}
						else if (name == "ItemGroup")
						{
							// TODO: wild card support

							foreach (System.Xml.XmlNode itemGroupChild in projectComponent.ChildNodes)
							{
								string itemName = itemGroupChild.Name;
								if (itemName == "Compile")
								{
									foreach (System.Xml.XmlAttribute attribute in itemGroupChild.Attributes)
									{
										if (attribute.Name == "Include")
										{
											codeFiles.Add(attribute.Value);
										}
									}
								}
								else if (itemName == "Reference")
								{
									// TODO: ensure only allowed references are used.
								}
								else if (itemName == "EmbeddedResource")
								{
									foreach (System.Xml.XmlAttribute attribute in itemGroupChild.Attributes)
									{
										if (attribute.Name == "Include")
										{
											embedFiles.Add(attribute.Value);
										}
									}
								}
							}
						}
					}
				}
			}

			return new CsProjData(directory, codeFiles, embedFiles);
		}
	}
}
